args=commandArgs(T)

TCRDirListi=args[1]  #BCR 
outTCRFile=args[2]   #BCR
flag=args[3]  #1,all; 2:1A1B,1A2B,2A1B 3:only 1A0B or 0A1B 4:all.XAXB

#output two files:
#BCRTable and BCRTable.barcode

#BCRDirListi:
#P4_Ptumor_	/data2/users/dongxingjun/Human_SC_AnaData/P4/Ptumor/TCR/outs

#finish in 2020.2.26,add c_gene
#from cellrange's BCR analysis data get BCR Table

readList <- function(LTable){
  a <- read.table(LTable,sep = "\t")
  sampleList  <- as.vector(a$V1)
  b <- as.vector(a$V2)
  names(b) <- as.vector(a$V1)
  return(b)
}


readTCR <- function(data.dir=NULL,CellType=NULL)
{
  #get all TCR info
  
  contig.loc <- paste0(data.dir,"/filtered_contig_annotations.csv")
  contig <- read.csv(contig.loc)
  all.cell <- as.vector(contig[,1])
 
  #filter cell 
  contig[,1]=all.cell
  productiveA.cell <- unique(all.cell[which(contig$productive=="true" & contig$chain=="IGH")])
  productiveB1.cell <- unique(all.cell[which(contig$productive=="true" & contig$chain=="IGK")])
  productiveB2.cell <- unique(all.cell[which(contig$productive=="true" & contig$chain=="IGL")])

  choCells <- union(productiveA.cell,productiveB1.cell)
  choCells <- union(choCells,productiveB2.cell)
  commIGKLBar <- intersect(productiveB1.cell,productiveB2.cell)
  #stri <- paste("have IGK and IGL barcode:",length(commIGKLBar),sep="")
  #print(stri)
  #print(commIGKLBar)

  #get filter infomation from choose cells
  id <- apply(contig[,c("v_gene","d_gene","j_gene","cdr3","c_gene")],1, function(x)paste(x,collapse = ":")
  )
  clonotype2cell <- cbind(id,contig[,c("barcode","chain","raw_clonotype_id")])[which(contig$productive=="true"),]
  clonotype2cell <- clonotype2cell[which(clonotype2cell$barcode %in% choCells),]

  #get all.BCR.srt
  all.BCR.srt=lapply(unique(clonotype2cell$barcode),function(x)
  {
    idx=which(clonotype2cell$barcode==x)
    BCR=clonotype2cell[idx,]
    
    BRA=BCR[which(BCR$chain=="IGH"),"id"]
    BRA.count=length(BRA)
    BRA=paste(BRA,collapse = "|")
  
    BChain = c("IGK","IGL")  
    BRB=BCR[which(BCR$chain %in% BChain),"id"]
    BRB.count=length(BRB)
    BRB=paste(BRB,collapse = "|")

    BRK.count=length(BCR[which(BCR$chain=="IGK"),"id"])
    BRL.count=length(BCR[which(BCR$chain=="IGL"),"id"])
    
    BCR.id=paste(BRA,BRB,sep=";")
    Tcount=BRA.count+BRB.count
    
    #BCR.stat = paste(BRA.count,"H",BRK.count,"K",BRL.count,"L",sep="")
    BCR.stat = paste(BRA.count,"A",BRB.count,"B",sep="")
    
    c(BCR.id,BRA.count,BRB.count,Tcount,BCR.stat)
    
  })

  #barcode name
  all.BCR.srt=do.call(rbind,all.BCR.srt)
  barcode <- unique(clonotype2cell$barcode)
  barcode <- paste(CellType,barcode,sep="")
  rownames(all.BCR.srt) = barcode
  
  #final
  finalTable = as.data.frame(all.BCR.srt)
  finalTable = cbind(barcode,finalTable)
  TableColName <- c("barcode","BCRid","ACount","BCount","TotCount","BCRstat")
  colnames(finalTable) <- TableColName

  return(finalTable)
}

#main
a <- readList(TCRDirListi)
cellTypeList <- names(a)

#for every sample
finalTable <- NULL
for(i in seq(1,length(cellTypeList),1))
{
  celltype <- cellTypeList[i]
  dataDir <- as.character(a[i])

  print(celltype)
  print(dataDir)
  tempTable <- readTCR(data.dir=dataDir,CellType=celltype)      
  finalTable <- rbind(finalTable,tempTable)
}

#filter
if(flag == 1)
{
  #all
  print("all kinds of BCR barcode:")
  finalTable <- finalTable
}else if(flag == 2)
{
  print("BCR:1A1B,2A1B,1A2B:")
  #1A1B,2A1B,1A2B
  finalTable <- finalTable[which(finalTable$ACount %in% c(1,2) & finalTable$BCount %in% c(1,2) & finalTable$TotCount %in% c(2,3)),]
}else if(flag == 3)
{
  print("BCR:1A0B,0A1B:")
  #only 1A0B or 0A1B
  finalTable <- finalTable[which(finalTable$ACount %in% c(0,1) & finalTable$BCount %in% c(0,1) & finalTable$TotCount %in% c(1)),]
}


#output final table
write.table(finalTable,file = outTCRFile,row.names = F,col.names = T,sep="\t",quote=F)
outBar <- paste(outTCRFile,".StandBCR.Bar",sep="")
print(outBar)
outBarBCRStat <- c("1A1B","1A2B","2A1B","2A2B")
writeLines(as.vector(finalTable[which(finalTable$BCRstat %in% outBarBCRStat),]$barcode),con=outBar,sep="\n")
#writeLines(as.vector(finalTable$barcode),con=outBar,sep="\n")

